package com.javaweb.blogcite.aspect;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.javaweb.blogcite.pojo.Admin;
import com.javaweb.blogcite.util.JwtTokenUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class JwtAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtAspect.class);

    private static final String tokenHeader = "Authorization";
    private static final String tokenHead = "Bearer ";

    @Around("@annotation(JwtCheck)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String authHeader = request.getHeader(tokenHeader);
        if (authHeader!= null && authHeader.startsWith(tokenHead)) {
            String authToken = authHeader.substring(tokenHead.length());
            String Id = JwtTokenUtil.getUserNameFromToken(authToken);
            LOGGER.info("checking Id: " + Id);
            if (Id!= null) {
                Admin admin = new Admin();
                admin.setId(Id);
                if (JwtTokenUtil.validateToken(authToken, admin)) {
                    // 验证Token成功，放行方法调用
                    return joinPoint.proceed();
                }
            }
        }
        // 返回消息进行处理，模拟未登录的情况返回相应信息
        Map<String, Object> map = new HashMap<>();
        map.put("code", 403);
        map.put("msg", "用户未登录");
        map.put("state", false);
        String json = new ObjectMapper().writeValueAsString(map);

        // 设置响应相关信息，返回给客户端
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        servletRequestAttributes.getResponse().setContentType("application/json;charset=UTF-8");
        servletRequestAttributes.getResponse().getWriter().println(json);

        return null;
    }
}
